define(['app'], function(app) {
    app.controller('AceSearchboxController', function($timeout, xContext, $uibModalInstance, toastr) {
        var self = this;
        self.context = {
            needle: '',
            replace: '',
            backwards: false,
            wrap: true,
            caseSensitive: false,
            wholeWord: false,
            range: null,
            regExp: false,
            skipCurrent: true
        };

        var editor = null;

        self.init = function() {
            editor = xContext.editor;
            self.context.needle = xContext.context;
            $uibModalInstance.rendered.then(function() {
                var jqDialog = jQuery('#ace-searchbox').parents('div.modal');
                jqDialog.draggable({
                    cursor: 'move',
                    handle: '.modal-header'
                });
                jqDialog.css('overflow', 'hidden');
                jqDialog.css('left', (jQuery(window).width() - jqDialog.width()) / 2 + 'px');
            });

            xContext.scope.$watch('vm.searchText', function(newValue) {
                self.context.needle = newValue;
                $timeout(function() {
                    jQuery('#ace-searchbox [name="needle"]').select();
                });
            }, true);
        }

        function find() {
            if (editor.find(self.context.needle, self.context)) {
                return true;
            }
            toastr.warning('找不到【' + self.context.needle + '】！');
            return false;
        }

        self.execute = function(valid) {
            if (valid) {
                find();
            }
        }

        self.find = function() {
            find();
        }

        self.replace = function() {
            var range = editor.replace(self.context.replace);
            // find next
            find();
        }

        self.replaceAll = function() {
            if (find()) {
                editor.replaceAll(self.context.replace);
            }
        }

        self.close = function() {
            $uibModalInstance.close();
        }
    });
});
